package com.example.demo.controller;

import com.example.demo.common.AppVariable;
import com.example.demo.common.PasswordUtils;
import com.example.demo.common.ResultAjax;
import com.example.demo.model.Userinfo;
import com.example.demo.model.vo.UserinfoVO;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * Description
 * User: 杰
 * Date: 2023 -08 -12
 * Time: 17:48
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    // 注册
    @RequestMapping("/reg")
    public ResultAjax reg(Userinfo userinfo) {
        // 1. 先校验参数
        if (userinfo == null || !StringUtils.hasLength(userinfo.getPassword()) ||
            !StringUtils.hasLength(userinfo.getUsername())) {
            // 参数有误
            return ResultAjax.fail(-1,"非法参数");
        }
        // 对密码进行加密
        userinfo.setPassword(PasswordUtils.encrypt(userinfo.getPassword()));
        // 2. 调用 service 进行添加用户操作
        int result = userService.reg(userinfo);
        // 3. 返回结果给前端
        return ResultAjax.succ(result);
    }

    // 登录接口
    @RequestMapping("/login")
    public ResultAjax login(UserinfoVO userinfoVO, HttpServletRequest request) {
        // 首先进行参数校验
        if (userinfoVO == null || !StringUtils.hasLength(userinfoVO.getUsername()) ||
            !StringUtils.hasLength(userinfoVO.getPassword())) {
            // 参数不正确, 非法登录
            return ResultAjax.fail(-1,"非法参数");
        }
        // 根据用户名查询对象
        Userinfo userinfo = userService.getUserByName(userinfoVO.getUsername());
        if (userinfo == null || userinfo.getId() == 0) {
            // 该用户不存在
            return ResultAjax.fail(-2,"用户名或密码错误!");
        }
        // 对象中的密码 与 用户输入的密码进行比较
        // 加盐解密
        if (!PasswordUtils.decrypt(userinfoVO.getPassword(),userinfo.getPassword())) {
            // 密码错误
            return ResultAjax.fail(-2,"用户名或者密码错误");
        }
        // 比较成功后,将对象存储到 session中.
        HttpSession session = request.getSession();
        session.setAttribute(AppVariable.SESSION_USERINFO_KEY,userinfo);
        // 结果进行返回
        return ResultAjax.succ(1);
    }

    // 注销
    @RequestMapping("/logout")
    public ResultAjax logout(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null || session.getAttribute(AppVariable.SESSION_USERINFO_KEY) != null) {
            session.removeAttribute(AppVariable.SESSION_USERINFO_KEY);
        }
        return ResultAjax.succ(1);
    }
}
